import config from './config.js'

class Http {
	constructor() {
		this.config = config
		this.interceptors = {
			request: null,
			response: null
		}
	}

	// 设置请求拦截器
	setRequestInterceptor(interceptor) {
		this.interceptors.request = interceptor
	}

	// 设置响应拦截器
	setResponseInterceptor(interceptor) {
		this.interceptors.response = interceptor
	}

	// 请求方法
	async request(options) {
		// 显示 loading
		if (options.showLoading) {
			uni.showLoading({
				title: '加载中...',
				mask: true,
			})
		}
		try {
			// 合并配置
			options = {
				...this.config,
				...options,
				url: this.config.baseUrl + options.url,
				header: {
					...this.config.headers,
					...(options.header || {})
				}
			}
			// 请求拦截
			if (this.interceptors.request) {
				options = await this.interceptors.request(options)
			}

			return new Promise((resolve, reject) => {
				uni.request({
					...options,
					success: async (res) => {
						// 响应拦截
						if (this.interceptors.response) {
							try {
								res = await this.interceptors.response(res)

								if (res.code != 200) {
									uni.showToast({
										title: res.msg,
										icon: 'none'
									})
								}
								resolve(res)

							} catch (error) {
								reject(error)
								uni.showToast({
									title: res.data.msg,
									icon: 'error'
								})
							}
						} else {
							resolve(res)
						}
					},
					fail: (err) => {
						reject(err)
					}
				})
			})
		} finally {
			// 隐藏 loading
			if (options.showLoading !== false) {
				setTimeout(function(){
					uni.hideLoading()
				},500)
				
			}
		}

	}

	// GET 请求
	get(url, data, token, showLoading) {
		if (token) {
			if (!data) {
				data = {}
			}
			data.user_token = uni.getStorageSync('user_token')
		}
		return this.request({
			url,
			data,
			method: 'GET',
			showLoading
		})
	}

	// POST 请求
	post(url, data, token, showLoading) {
		if (token) {
			if (!data) {
				data = {}
			}
			data.user_token = uni.getStorageSync('user_token')
		}
		return this.request({
			url,
			data,
			method: 'POST',
			showLoading
		})
	}
	// H5环境辅助方法：将路径转换为File对象
	getFileFromPath = (filePath) => {
		return new Promise((resolve) => {
			// 这里需要根据实际路径获取文件
			// 如果是H5的临时路径，可能需要特殊处理
			const xhr = new XMLHttpRequest()
			xhr.open('GET', filePath, true)
			xhr.responseType = 'blob'
			xhr.onload = () => {
				const blob = xhr.response
				const file = new File([blob], 'avatar.jpg', {
					type: blob.type
				})
				resolve(file)
			}
			xhr.send()
		})
	}
	//upload file
	async upload(url, data, token, showLoading) {
		const formData = new FormData()
		const file = await this.getFileFromPath(data.file)
		formData.append('file', file)
		formData.append('user_token', uni.getStorageSync('user_token'));
		const res = await fetch(this.config.baseUrl + url, {
			method: 'POST',
			body: formData,
			header: {
				'Authorization': 'Bearer ' + uni.getStorageSync('user_token')
			}
		})
		const result = await res.json()
		return result;
	}

	// PUT 请求
	put(url, data, token, showLoading) {
		if (token) {
			if (!data) {
				data = {}
			}
			data.user_token = uni.getStorageSync('user_token')
		}
		return this.request({
			url,
			data,
			method: 'PUT',
			showLoading
		})
	}

	// DELETE 请求
	delete(url, data, showLoading) {
		return this.request({
			url,
			data,
			method: 'DELETE',
			showLoading
		})
	}
}

export default new Http()